<template>
  <view class="user-container">
    <!-- 用户信息卡片 -->
    <view class="user-card" @click="navigateTo('/pages/user/profile/index')">
      <view class="user-info">
        <image :src="userInfo.avatar || '/static/images/default-avatar.png'" class="avatar"></image>
        <view class="info">
          <block v-if="isLoggedIn">
            <text class="nickname">{{ userInfo.nickname || '未设置昵称' }}</text>
            <text class="userid" v-if="userInfo.id">ID: {{ userInfo.id }}</text>
          </block>
          <block v-else>
            <text class="nickname">未登录</text>
            <text class="login-tip">点击登录账号</text>
          </block>
        </view>
        <uni-icons type="right" size="24" color="#999"></uni-icons>
      </view>
    </view>

    <!-- 功能菜单 -->
    <view class="menu-section">
      <view class="menu-group">
        <view class="menu-item" @click="goMySpace">
          <uni-icons type="home" size="40" color="#ff4757"></uni-icons>
          <text>我的空间</text>
        </view>
        <view class="menu-item" @click="navigateTo('/pages/order/list/index?type=all')">
          <uni-icons type="cart" size="40" color="#ff5500"></uni-icons>
          <text>我的订单</text>
        </view>
        <view class="menu-item" @click="navigateTo('/pages/user/favorite/index')">
          <uni-icons type="star" size="40" color="#ff9900"></uni-icons>
          <text>我的收藏</text>
        </view>
        <view class="menu-item" @click="handleAddressClick">
          <uni-icons type="location" size="40" color="#33cc99"></uni-icons>
          <text>收货地址</text>
        </view>
        <view class="menu-item" @click="navigateTo('/pages/user/history/index')">
          <uni-icons type="eye-filled" size="40" color="#9966ff"></uni-icons>
          <text>浏览历史</text>
        </view>
        <view class="menu-item" @click="handleMessageClick">
          <uni-icons type="notification-filled" size="40" color="#ff5500"></uni-icons>
          <text>我的消息</text>
          <view v-if="unreadMessageCount > 0" class="badge">{{ unreadMessageCount }}</view>
        </view>
        <view class="menu-item" @click="navigateTo('/pages/user/merchant/apply')">
          <uni-icons type="shop" size="40" color="#ff9500"></uni-icons>
          <text>成为商家</text>
        </view>
      </view>
    </view>
    
    <!-- 退出登录按钮 -->
    <button class="logout-btn" @click="handleLogout" v-if="isLoggedIn">退出登录</button>
  </view>
</template>

<script>
import { getUserInfo, isLoggedIn, clearLoginInfo } from '@/utils/auth'

export default {
  data() {
    return {
      userInfo: {},
      isLoggedIn: false,
      // 地址管理相关路由配置
      addressRoutes: {
        list: '/pages/user/address/index',
        add: '/pages/user/address/add',
        edit: '/pages/user/address/edit'
      },
      // 添加消息相关路由配置
      messageRoutes: {
        system: '/pages/user/message/system',
        chat: '/pages/user/message/chat'
      },
      unreadMessageCount: 0
    }
  },
  onShow() {
    this.loadUserInfo()
    // 如果已登录，加载未读消息数
    if (this.isLoggedIn) {
      this.loadUnreadMessageCount()
    }
  },
  methods: {
    loadUserInfo() {
      this.isLoggedIn = isLoggedIn()
      if (this.isLoggedIn) {
        this.userInfo = getUserInfo() || {}
      } else {
        this.userInfo = {}
      }
    },
    // 处理地址管理相关导航
    handleAddressClick() {
      if (!this.isLoggedIn) {
        // 未登录时保存当前页面并跳转到登录页
        const pages = getCurrentPages()
        const currentPage = pages[pages.length - 1]
        if (currentPage && currentPage.route) {
          uni.setStorageSync('loginRedirect', `/${currentPage.route}`)
        }
        
        uni.navigateTo({
          url: '/pages/user/auth/login'
        })
        return
      }

      // 已登录则跳转到地址列表页
      uni.navigateTo({
        url: this.addressRoutes.list,
        success: () => {
          console.log('成功跳转到地址管理页面')
        },
        fail: (error) => {
          console.error('跳转到地址管理页面失败:', error)
          uni.showToast({
            title: '页面跳转失败',
            icon: 'none'
          })
        }
      })
    },
    // 统一的页面导航方法
    navigateTo(url) {
      // 检查是否需要登录
      if (!this.isLoggedIn && !url.includes('/auth/')) {
        // 保存当前页面路径
        const pages = getCurrentPages()
        const currentPage = pages[pages.length - 1]
        if (currentPage && currentPage.route) {
          uni.setStorageSync('loginRedirect', `/${currentPage.route}`)
        }
        
        // 跳转到登录页
        uni.navigateTo({
          url: '/pages/user/auth/login'
        })
        return
      }
      
      try {
        // 使用 navigateTo 进行页面跳转
        uni.navigateTo({ 
          url,
          fail: (error) => {
            console.error('页面跳转失败:', error)
            uni.showToast({
              title: '页面跳转失败',
              icon: 'none'
            })
          }
        })
      } catch (error) {
        console.error('导航错误:', error)
        uni.showToast({
          title: '页面跳转失败',
          icon: 'none'
        })
      }
    },
    async handleLogout() {
      try {
        const res = await uni.showModal({
          title: '提示',
          content: '确定要退出登录吗？'
        })
        
        if (!res.confirm) return
        
        // 显示加载提示
        uni.showLoading({
          title: '退出中...',
          mask: true
        })
        
        // 调用退出登录接口
        await this.$api.user.auth.logout()
        
        // 清除本地存储的用户信息
        uni.removeStorageSync('token')
        uni.removeStorageSync('userInfo')
        
        // 刷新页面状态
        this.isLoggedIn = false
        this.userInfo = {}
        
        uni.hideLoading()
        uni.showToast({
          title: '已退出登录',
          icon: 'success'
        })
        
        // 延迟跳转到首页
        setTimeout(() => {
          uni.reLaunch({
            url: '/pages/index/index'
          })
        }, 1500)
      } catch (error) {
        console.error('退出登录失败:', error)
        uni.hideLoading()
        uni.showToast({
          title: error.message || '退出失败',
          icon: 'none'
        })
      }
    },
    goMySpace() {
      if (!this.checkLogin()) return
      uni.navigateTo({
        url: '/pages/community/user/index'
      })
    },
    
    checkLogin() {
      if (!this.isLoggedIn) {
        // 保存当前页面路径
        const pages = getCurrentPages()
        const currentPage = pages[pages.length - 1]
        if (currentPage && currentPage.route) {
          uni.setStorageSync('loginRedirect', `/${currentPage.route}`)
        }
        
        // 跳转到登录页
        uni.navigateTo({
          url: '/pages/user/auth/login'
        })
        return false
      }
      return true
    },
    // 加载未读消息数
    async loadUnreadMessageCount() {
      try {
        const res = await this.$api.message.getUnreadCount()
        if (res.code === 200) {
          this.unreadMessageCount = res.data || 0
        }
      } catch (error) {
        console.error('获取未读消息数失败:', error)
      }
    },
    // 处理消息点击
    handleMessageClick() {
      if (!this.checkLogin()) return
      
      // 默认跳转到私信页面
      uni.navigateTo({
        url: this.messageRoutes.chat
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.user-container {
  min-height: 100vh;
  background-color: #f7f9fc;
  padding-bottom: env(safe-area-inset-bottom);
}

.user-card {
  position: relative;
  background: linear-gradient(135deg, #8ab5e8, #6c9bd1);
  padding: 40rpx 30rpx;
  margin-bottom: 20rpx;
  border-radius: 0 0 30rpx 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(108, 155, 209, 0.15);

  .user-info {
    display: flex;
    align-items: center;
    
    .avatar {
      width: 120rpx;
      height: 120rpx;
      border-radius: 50%;
      border: 4rpx solid rgba(255, 255, 255, 0.4);
      box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.08);
    }

    .info {
      flex: 1;
      margin-left: 24rpx;

      .nickname {
        font-size: 36rpx;
        color: #fff;
        font-weight: 600;
        margin-bottom: 8rpx;
      }

      .userid, .login-tip {
        font-size: 24rpx;
        color: rgba(255, 255, 255, 0.9);
      }
    }

    :deep(.uni-icons) {
      color: rgba(255, 255, 255, 0.9) !important;
    }
  }
}

.menu-section {
  background-color: #fff;
  border-radius: 20rpx;
  margin: 20rpx;
  padding: 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(108, 155, 209, 0.08);

  .menu-group {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 30rpx 20rpx;
    padding: 20rpx 0;

    .menu-item {
      position: relative;
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 12rpx;
      padding: 20rpx 0;
      transition: transform 0.2s;

      &:active {
        transform: scale(0.95);
      }

      text {
        font-size: 26rpx;
        color: #445167;
        font-weight: 500;
      }

      .badge {
        position: absolute;
        top: 0;
        right: 50%;
        transform: translateX(20rpx);
        min-width: 32rpx;
        height: 32rpx;
        border-radius: 16rpx;
        background: #f17a7a;
        color: #fff;
        font-size: 20rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0 8rpx;
      }

      :deep(.uni-icons) {
        background: #f0f5fc;
        width: 80rpx;
        height: 80rpx;
        border-radius: 20rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 8rpx;
        transition: all 0.3s;

        // 修改图标颜色
        &[type="home"] { color: #7eb6e6 !important; }
        &[type="cart"] { color: #89c4a1 !important; }
        &[type="star"] { color: #e6b17e !important; }
        &[type="location"] { color: #7eb6e6 !important; }
        &[type="eye-filled"] { color: #a593e6 !important; }
        &[type="notification-filled"] { color: #e6917e !important; }
        &[type="shop"] { color: #7ec4e6 !important; }
      }
    }
  }
}

.logout-btn {
  width: calc(100% - 40rpx);
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  font-size: 30rpx;
  color: #6c9bd1;
  background: #fff;
  border-radius: 44rpx;
  margin: 40rpx auto;
  box-shadow: 0 4rpx 16rpx rgba(108, 155, 209, 0.08);
  border: none;
  transition: all 0.3s;

  &:active {
    transform: scale(0.98);
    background: #f0f5fc;
  }
}
</style> 